package sg.edu.nus.iss.vmcs.store;

import java.util.Iterator;

/*
 * Copyright 2003 ISS.
 * The contents contained in this document may not be reproduced in any
 * form or by any means, without the written permission of ISS, other
 * than for the purpose for which it has been supplied.
 *
 */

/**
 *class CashStore extends Store
 *This object represents the store of cash in the vending machine. 
 * @version 3.0 5/07/2003
 * @author Olivo Miotto, Pang Ping Li
 */

public class CashStore extends Store {
	
	private static CashStore instance;

	public final static int INVALID_COIN_WEIGHT = 9999;
	public static int DESCENDING=3;
/**
 * This constructor creates a new instance of the Cash Store. 
 * It creates the required number of instances of Cash Store Item 
 * and Coin objects 
 *
 */
	private CashStore() {
	}
	
	public static CashStore getInstance(){
		if(instance==null)
			instance=new CashStore();
		
		return instance;
	}
	
	
/**
 * int = findCashStoreIndex(Coin c);
 * This operation is used to find the index to a Cash Store Item for a specific Coin
 * @param c: Coin Object 
 * @return integer representing the index of the coin object in the cash store.
 */	
	public int findCashStoreIndex (Coin c) {
		int size = getStoreSize();
		for (int i = 0; i < size; i++) {
			StoreItem item = (CashStoreItem) getStoreItem(i);
			Coin current = (Coin) item.getContent();
			if (current.getWeight() == c.getWeight())
				return i;
		}
		return -1;
	}
	
/**
 * Coin = findCoin(Integer weight)
 * This operation will locate a coin denomination held, with the input data (coin weight).
 * If found, it returns an existence identifier (reference). Otherwise, it informs 
 * the requestor that the coin is invalid. 
 * @param weight: Integer value of the weight of the coin. the double [weight] is 
 * converted into integer by function intvalue()
 * @return Coin: This coin object represents the coin with weight given in the argument
 */	
	public Coin findCoin(Integer weight){		
		CashStore cStore=this;
		StoreItem[] items=cStore.getItems();
		for(int i=0;i<items.length;i++){
			Coin coin=(Coin)items[i].getContent();
			Double w=coin.getWeight();
			Integer intW=w.intValue();
			if(intW.compareTo(weight)==0){
				return coin;
			}
		}
		return null;
	}
	
	//Iterator Pattern
	public Iterator createIterator(int type)
	{
		if(type== NONEMPTY)
			return new NonEmptyQtyIterator(getItems());
		else if(type==NORMALITERATOR)
			return new NormalIterator(getItems());
		else if (type == DESCENDING)
			return new CSDescendingIterator(getItems());
		else return null;
	}
	
}

